/*

 * Licensed to the Apache Software Foundation (ASF) under one

 * or more contributor license agreements.  See the NOTICE file

 * distributed with this work for additional information

 * regarding copyright ownership.  The ASF licenses this file

 * to you under the Apache License, Version 2.0 (the

 * "License"); you may not use this file except in compliance

 * with the License.  You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package com.bff.gaia.unified.runners.gaia.translation.wrappers.streaming.io;



import com.bff.gaia.unified.sdk.util.WindowedValue;

import com.bff.gaia.unified.sdk.values.ValueWithRecordId;

import com.bff.gaia.api.common.state.ValueState;

import com.bff.gaia.api.common.state.ValueStateDescriptor;

import com.bff.gaia.api.common.typeutils.base.LongSerializer;

import com.bff.gaia.runtime.state.StateInitializationContext;

import com.bff.gaia.runtime.state.VoidNamespace;

import com.bff.gaia.runtime.state.VoidNamespaceSerializer;

import com.bff.gaia.streaming.api.operators.*;

import com.bff.gaia.streaming.runtime.streamrecord.StreamRecord;

import org.joda.time.Duration;



import java.nio.ByteBuffer;



/** Remove values with duplicate ids. */

public class DedupingOperator<T> extends AbstractStreamOperator<WindowedValue<T>>

    implements OneInputStreamOperator<WindowedValue<ValueWithRecordId<T>>, WindowedValue<T>>,

        Triggerable<ByteBuffer, VoidNamespace> {



  private static final long MAX_RETENTION_SINCE_ACCESS = Duration.standardMinutes(10L).getMillis();



  // we keep the time when we last saw an element id for cleanup

  private ValueStateDescriptor<Long> dedupingStateDescriptor =

      new ValueStateDescriptor<>("dedup-cache", LongSerializer.INSTANCE);



  private transient InternalTimerService<VoidNamespace> timerService;



  @Override

  public void initializeState(StateInitializationContext context) throws Exception {

    super.initializeState(context);



    timerService =

        getInternalTimerService("dedup-cleanup-timer", VoidNamespaceSerializer.INSTANCE, this);

  }



  @Override

  public void processElement(StreamRecord<WindowedValue<ValueWithRecordId<T>>> streamRecord)

      throws Exception {



    ValueState<Long> dedupingState = getPartitionedState(dedupingStateDescriptor);



    Long lastSeenTimestamp = dedupingState.value();



    if (lastSeenTimestamp == null) {

      // we have never seen this, emit

      WindowedValue<ValueWithRecordId<T>> value = streamRecord.getValue();

      output.collect(streamRecord.replace(value.withValue(value.getValue().getValue())));

    }



    long currentProcessingTime = timerService.currentProcessingTime();

    dedupingState.update(currentProcessingTime);

    timerService.registerProcessingTimeTimer(

        VoidNamespace.INSTANCE, currentProcessingTime + MAX_RETENTION_SINCE_ACCESS);

  }



  @Override

  public void onEventTime(InternalTimer<ByteBuffer, VoidNamespace> internalTimer) {

    // will never happen

  }



  @Override

  public void onProcessingTime(InternalTimer<ByteBuffer, VoidNamespace> internalTimer)

      throws Exception {

    ValueState<Long> dedupingState = getPartitionedState(dedupingStateDescriptor);



    Long lastSeenTimestamp = dedupingState.value();

    if (lastSeenTimestamp != null

        && lastSeenTimestamp.equals(internalTimer.getTimestamp() - MAX_RETENTION_SINCE_ACCESS)) {

      dedupingState.clear();

    }

  }

}